// 主页

import api from '../../../utils/api'

var app = getApp();
Page({


  /**
   * 页面的初始数据
   */
  data: {
    host: app.globalData.host,
    isloadmain: false,
    banners:[],
    themes: [],
    recomme:[],
    hasMore: true,
    pageNo: 1,
    list: []
  },

  //获取用户信息
  _loadUserInfo: function (cb) {
    var that = this;
    var userInfo = wx.getStorageSync('USER_INFO');

    wx.login({
      success: function (ret) {
        var code = ret.code;
        wx.getUserInfo({
          success: function (res) {
            var data = {
              code: code,
              encryptedData: res.encryptedData,
              iv: res.iv
            };
            api.request('/user/decrypt', 'POST', data, (res) => {
              wx.setStorageSync('USER_INFO', res.data.data);
              wx.setStorageSync('USER_TOKEN', res.data.data.token);
              console.log(' USER_TOKEN Success! ');
            });

          }
        })
      }
    })
  },


  _login: function () {

    wx.login({
      success: function (ret) {
        var code = ret.code;
        var data = {"code":code};
        api.request('/user/login_code', 'POST', data, (res) => {
          wx.setStorageSync('USER_INFO', res.data.data);
          wx.setStorageSync('USER_TOKEN', res.data.data.token);
          console.log(' USER_TOKEN Success! ');
        });
      }
    })
  },

  //token校验
  _checkToken(){
    var that = this;
    var userToken = wx.getStorageSync('USER_TOKEN');
    api.request('/user/check', 'POST', {
      token: userToken
    }, (res) => {
      console.log(res.data.check);
      var checkStatus = res.data.check;
      //如果校验失败
      if (!checkStatus) {
        that._login();
        console.log('校验失败');
      }
    });
  },

  _autoLogin: function(){
    var userInfo = wx.getStorageSync('USER_INFO');
    if (!userInfo) {
      //第一次进入小程序
      this._loadUserInfo();
    }else{
      //token校验
      this._checkToken();
    }
  },

  //主题跳转
  to_list(e){
    var group_id = e.currentTarget.dataset.id;
    var title = e.currentTarget.dataset.title;
    var img = e.currentTarget.dataset.img;
    wx.navigateTo({
      url: '../../list/index/index?id=' + group_id + '&title=' + title + '&img=' + img,
    })
  },

  //请求轮播图
  _load_banner(){
    var that = this;
    api.request('/shop/slides', 'GET', {}, (res) => {
      console.log('轮播图数据：', res.data.data)
      var banner_arr = res.data.data;
      that.setData({
        banners: banner_arr
      })
    })
  },

  // 点击轮播图
  listlook(e){
    console.log(e.currentTarget.dataset.id)
    console.log(e.currentTarget.dataset.type)
    let type = e.currentTarget.dataset.type;
    let type_id = e.currentTarget.dataset.id;
    let title = e.currentTarget.dataset.title;
    let img = e.currentTarget.dataset.img;
    if (type == 'detail'){
      // 跳转到详情页面
      wx.navigateTo({
        url: '../../detail/index/index?id=' + type_id
      })
    } else if (type == 'group'){
      // 跳转到专题页面
      wx.navigateTo({
        url: '../../list/index/index?id=' + type_id + '&title=' + title + '&img=' + img,
      })
    }else{}
  },

  //请求今日推荐
  _load_recom(){
    var that = this;
    api.request('/shop/pro_top', 'GET', {
      page:1,
      row:5
    }, (res) => {
      that.setData({
        recomme: res.data.data,
        hasMore: res.data.has_more
      })
    })
  },

  //请求商品专题
  _load_theme(){
    var that = this;
    api.request('/shop/groups', 'GET', {}, (res) => {
      that.setData({
        themes: res.data.data,
        isloadmain: true
      })
    })
  },

  //查看今日推荐详情
  to_detail(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../../detail/index/index?id=' + id
    })
  },

  // 请求全部商品列表
  _load_all(){
    var that = this;
    api.request('/shop/pro_cat', 'GET', {
      page: that.data.pageNo,
      row: 10,
    }, (res) => {
      var list = that.data.list;
        if (res.data.data.length) {
          for (var i = 0; i < res.data.data.length; i++) {
            list.push(res.data.data[i]);
          }
        }
        that.setData({
          list: list,
          hasMore: res.data.has_more//判断是否有更多
        })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this._autoLogin()
    // 请求轮播图
    this._load_banner()
    //请求今日推荐
    this._load_recom()
    //请求主题
    this._load_theme()
    // 请求全部商品
    this._load_all()
  },
  
  //页面滚到底部
  onscrolltolower(){
    var that = this;
    that.data.pageNo++;
    if (that.data.hasMore) {
      that._load_all()
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})